import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';
import moment, { relativeTimeThreshold } from 'moment';
import printJS from 'print-js';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { addTab, timeScopeLimit } from '@/utils/utils';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Table,
  Button,
  Card,
  Col,
  Input,
  Row,
  Select,
  DatePicker,
  Modal,
  message,
  Tooltip,
} from 'antd';

import '@ant-design/compatible/assets/index.css';
import Pagination from '../../components/Pagination';
import PrintElemInfo from './components/PrintElem';
import { number } from 'prop-types';

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;

const { pathname } = window.location;

const batchPperation = [
  { label: '批量标记待盘点', path: 'taking_tagTaking' },
  { label: '批量取消待盘点', path: 'taking_tagTaking' },
  { label: '批量催取短信', path: 'taking_notifyDelaying' },
  { label: '批量签收', path: 'taking_orderSign' },
  { label: '批量标记退回', path: 'taking_orderBack' },
];

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  location: { query: any };
  logisCenterTaking: any;
  INITINFO: any;
  loading: boolean;
  screen: string;
}

interface TableListState {
  offlineDialog: boolean;
  current: number;
  pageSize: number | undefined;
  formValues: any;
  isCabinet: string;
  batchOperaction: any[];
  operationInfo: any;
  rowId: number;
  backDialog: boolean;
  note: string;
  reasonType: any;
}

/* eslint react/no-multi-comp:0 */
@connect(({
  logisCenterTaking,
  common: { INITINFO },
  global: { screen },
  loading,
}: any) => ({
  logisCenterTaking,
  INITINFO,
  screen,
  loading: loading.effects['logisCenterTaking/fetch'],
}))

class TableList extends React.Component<TableListProps, TableListState> {
  columns = [
    {
      title: '运单号',
      dataIndex: 'expCode',
      width: 120,
      render: (expCode: any) => (
        <Tooltip title={expCode}>
          <div className="wordOmit">{expCode}</div>
        </Tooltip>
      ),
    },
    {
      title: '收件人手机',
      dataIndex: 'consigneePhone',
      width: 120,
      render: (text: any) => text || '--',
    },
    {
      title: '盘点状态',
      dataIndex: 'takingStatusName',
      width: 80,
    },
    {
      title: '投递人',
      dataIndex: 'courierName',
      width: 120,
    },
    {
      title: '投递人手机',
      dataIndex: 'courierPhone',
      width: 120,
    },
    {
      title: '入库时间',
      dataIndex: 'inTime',
      width: 160,
    },
    {
      title: '存放位置',
      dataIndex: 'address',
      width: 150,
      render: (text: any, record: any) => {
        const pkgNum = record.pkgNum === '0' || !record.pkgNum ? '' : ` ${record.pkgNum}`;
        const pkgText = record.storageType !== 5 ? pkgNum : '';
        const address = text ? text + pkgText : '--';
        return (
          <Tooltip title={address}>
            <div className="wordOmit namelink">{address}</div>
          </Tooltip>
        );
      },
    },
    {
      title: '快递公司',
      dataIndex: 'expressName',
      width: 100,
      render: (text: any) => text || '--',
    },
    {
      title: '是否到付',
      dataIndex: 'payment',
      width: 80,
      render: (text: number) => (text ? '是' : '否'),
    },
    {
      title: '批次号',
      dataIndex: 'batchName',
      width: 120,
      render: (text: number) => text || '--',
    },
  ];

  timer: any = null;

  state: TableListState = {
    current: 1,
    pageSize: 20,
    formValues: {},
    isCabinet: '',
    offlineDialog: false,
    batchOperaction: [],
    operationInfo: {},
    rowId: 0,
    backDialog: false,
    note: '',
    reasonType: '0',
  };

  static getDerivedStateFromProps(props: any, state: any) {
    const { search } = props.location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { page, psize, ...formValues } = query;

    return {
      ...state,
      formValues,
      current: Number(page) || 1,
      pageSize: Number(psize) || (props.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.searchShelves();
    this.searchCabinet();
    this.setFieldsValue();
    this.fetchProblemList();

    const { dispatch } = this.props;
    dispatch({ type: 'common/fetchLogisList' });
    dispatch({ type: 'common/fetchExpressList' });
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { formValues, current, pageSize } = this.state;
    if (!_.isEqual(formValues, prevState.formValues)
      || current !== prevState.current
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchProblemList();
    }
  }

  // 设置表单值
  setFieldsValue = () => {
    const { formValues } = this.state;

    const {
      minId,
      maxId,
      startTime,
      endTime,
      ...values
    } = formValues;

    if (startTime) {
      values.start_end_time = [moment(startTime), endTime ? moment(endTime) : moment(moment().format('YYYY/MM/DD HH:mm:ss'))];
    } else {
      values.start_end_time = [moment(moment().subtract(1, 'days').format('YYYY/MM/DD 00:00:00')), moment(moment().format('YYYY/MM/DD HH:mm:ss'))];
    }

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(values);
  };

  handleShowCount = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterTaking/fetchCount',
      payload: this.getQueryParams(),
    });
  };

  // 获取数据
  fetchProblemList = () => {
    const { location: { query } } = this.props;
    const { maxId, minId, ...other } = query;
    const search = qs.stringify(other);

    const { logisCenterTaking: { data } } = this.props;
    const { current } = this.state;
    const contentObj = data.content.find((item: any) => item.current === current);

    if (contentObj && search === contentObj.search) {
      this.setState({});
    } else {
      const { dispatch } = this.props;
      dispatch({
        type: 'logisCenterTaking/fetch',
        payload: {
          params: this.getQueryParams(),
          search,
          maxId,
          minId,
        },
      });
    }
  };

  // 获取查询参数
  getQueryParams = () => {
    const { formValues, current: pageIndex, pageSize } = this.state;
    const { shelves = {}, cabinet = {}, ...values } = formValues;
    const params = { ...values, pageIndex, pageSize };

    if (params.startTime === undefined) {
      params.startTime = moment()
        .subtract(1, 'days')
        .format('YYYY-MM-DD 00:00:00');
    }

    const key = shelves.key && shelves.key.split('|')[0];
    const type = shelves.key && shelves.key.split('|')[1];

    if (key && Number(key) !== 0) {
      params.storagePid = key;
      params.storageType = Number(type) === 0 ? 3 : 2;
    }

    if (cabinet.key && Number(cabinet.key) !== 0) {
      params.storagePid = cabinet.key;
      params.storageType = 1;
    }

    return params;
  };

  /** 批量操作 */
  handleBatchOperation = (offlineDialog: boolean, index: number = 0) => {
    const { batchOperaction } = this.state;
    if (batchOperaction.length <= 0) {
      message.warning('请先选择至少一条数据');
    } else if (index === 4) {
      this.setState({ backDialog: true, operationInfo: batchPperation[index] }, () => this.fetchWithdrawReasonList());
    } else {
      this.setState({ offlineDialog, operationInfo: batchPperation[index] });
    }
  };

  /** 确定操作 */
  handleConfirm = () => {
    const { batchOperaction, operationInfo } = this.state;
    const { location: { query } } = this.props;
    const { maxId, minId, ...other } = query;
    const search = qs.stringify(other);
    const idList = batchOperaction.map((item: any) => item.id).join(',');

    const params: any = {
      params: this.getQueryParams(),
      search,
      maxId,
      minId,
      idList,
      pathName: operationInfo.path,
    };

    if (operationInfo.path === 'taking_tagTaking') {
      const index = batchPperation.indexOf(operationInfo);
      params.isMark = Number(!index);
    }

    if (operationInfo.path === 'taking_orderBack') {
      const { reasonType, note } = this.state;
      if (reasonType === '0' || reasonType === 0) {
        message.error('请选择退回原因');
        return;
      }

      params.reasonType = reasonType;
      params.note = note;
    }

    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterTaking/batchOperation',
      payload: params,
    });

    this.setState({ batchOperaction: [] });
    this.handleBatchOperation(false);
    this.handleCloseSettingBack();
  };

  /** 导出 */
  handelExportExcel = () => {
    const params = this.getQueryParams();
    window.location.href = `/thanos/taking/exportExcel?${qs.stringify(params)}`;
  };

  /** 打印 */
  handleChangeVisble = () => {
    printJS({
      printable: 'billDetails',
      type: 'html',
      targetStyles: ['*'],
      onPrintDialogClose: () => '关闭',
      onError: error => error,
    });
  };

  /** 选择柜体 */
  handleChangeCabinet = (val: string) => {
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue({ shelves: undefined });
  };

  /** 选择货架 */
  handleChangeShelves = () => {
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue({ cabinet: undefined });
  };

  // 查询货架
  searchShelves = (name: string = '') => {
    if (name) {
      clearTimeout(this.timer);

      const { dispatch } = this.props;
      this.timer = setTimeout(() => {
        dispatch({
          type: 'common/fetchShelfList',
          payload: { name },
        });
      }, 500);
    }
  };

  // 查询柜体
  searchCabinet = (name: string = '') => {
    if (name) {
      clearTimeout(this.timer);

      const { dispatch } = this.props;
      this.timer = setTimeout(() => {
        dispatch({
          type: 'common/fetchCabinetList',
          payload: { name },
        });
      }, 500);
    }
  };

  /**
   * 选择器失去焦点
   */
  onBlurSelect = (fieldName: string, dataName: string) => {
    const { form: { getFieldValue } } = this.props;
    const fieldValue = getFieldValue(fieldName);

    const { INITINFO, form: { setFieldsValue } } = this.props;
    if (INITINFO[dataName].length && !fieldValue) {
      const key = INITINFO[dataName][0].id;
      const label = INITINFO[dataName][0].name;
      setFieldsValue({ [fieldName]: { key, label } });
    } else if (!INITINFO[dataName].length) {
      setFieldsValue({ [fieldName]: undefined });
    }
  };

  // 获取退回原因列表
  fetchWithdrawReasonList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchWithdrawReasonList',
      payload: {},
    });
  };

  /**
   * 关闭设置退回弹窗
   */
  handleCloseSettingBack = () => {
    this.setState({
      backDialog: false,
      note: '',
      reasonType: '0',
    });
  };

  /**
   * 选择问题件类型
   */
   handChangeReasonType = (reasonType: string) => {
    this.setState({ reasonType });
  };

  /**
   * 输入备注
   */
   handleChangeNote = (e: any) => {
    this.setState({ note: e.target.value });
  };

  /**
   * 查询
   */
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;

      const { start_end_time, ...params } = fieldsValue;

      if (params.seqNo && (!params.logisId || !params.expressId)) {
        message.warning('按批次查询时，必须同时指定物流中心和快递公司!');
        return;
      }

      const query = { page: 1, ...params };
      query.startTime = start_end_time[0]
        ? moment(start_end_time[0]).format('YYYY-MM-DD HH:mm:ss')
        : moment()
          .subtract(1, 'days')
          .format('YYYY-MM-DD 00:00:00');
      query.endTime = start_end_time[1] && moment(start_end_time[1]).format('YYYY-MM-DD HH:mm:ss');

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '盘点管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
      dispatch({ type: 'logisCenterTaking/cleanCount' });
    });
  };

  /**
   * 重置
   */
  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '盘点管理',
      url: pathname,
      isTopMenu: true,
    });
    dispatch({ type: 'logisCenterTaking/cleanCount' });
  };

  // 分页
  onSelectChange = (type: string) => {
    const { formValues, current, pageSize: psize } = this.state;
    const { logisCenterTaking: { data } } = this.props;

    const query = {
      ...formValues,
      page: type === 'prev' ? current - 1 : current + 1,
      psize,
    };

    const contentObj = data.content.find((item: any) => item.current === current);
    if (type === 'prev') {
      if (contentObj?.list?.length) {
        query.minId = contentObj.list[0].id;
      } else {
        const prevContentObj = data.content.find((item: any) => item.current === current - 1);
        const list = prevContentObj ? prevContentObj.list : [];
        query.preId = list[list.length - 1].id;
      }
      delete query.maxId;
    } else if (type === 'next') {
      const list = contentObj ? contentObj.list : [];
      query.maxId = list[list.length - 1].id;
      delete query.minId;
    }

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '盘点管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  // 选择显示行数
  onShowSizeChange = (pageSize: number) => {
    const { formValues } = this.state;
    const query = {
      ...formValues,
      page: 1,
      psize: pageSize,
    };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '盘点管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  // 渲染查询表单
  renderSearchFormElem() {
    const {
      form: { getFieldDecorator },
      INITINFO: {
        logisList, expressList, shelfList = [], cabinetList = [],
      },
    } = this.props;

    return (
      <Form onSubmit={this.handleSearch} className="tableListForm">
        <Row gutter={12}>
          <Col md={12} sm={24}>
            <FormItem label="　起止时间" colon={false}>
              {getFieldDecorator('start_end_time')(
                <RangePicker
                  showTime
                  placeholder={['开始时间', '截止时间']}
                  format="YYYY/MM/DD HH:mm:ss"
                  style={{ width: '100%' }}
                  disabledDate={timeScopeLimit}
                  ranges={{
                    今天: [moment().startOf('day'), moment().endOf('day')],
                    本周: [moment().startOf('week'), moment().endOf('week')],
                    本月: [moment().startOf('month'), moment().endOf('month')],
                    上月: [
                      moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                      moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                    ],
                  }}
                />,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="　物流中心" colon={false}>
              {getFieldDecorator('logisId')(
                <Select
                  showSearch
                  allowClear
                  placeholder="请选择"
                  filterOption={(input: any, option: any) => option.props.children
                    .toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {logisList.map((item: any) => (
                    <Option value={String(item.id)} key={item.id}>
                      {item.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="　快递公司" colon={false}>
              {getFieldDecorator('expressId')(
                <Select
                  showSearch
                  allowClear
                  placeholder="请选择"
                  filterOption={(input: any, option: any) => option.props.children
                    .toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {expressList.map((item: any) => (
                    <Option value={String(item.id)} key={item.id}>
                      {item.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <FormItem label="收件人手机" colon={false}>
              {getFieldDecorator('consigneePhone')(
                <Input
                  allowClear
                  type="number"
                  placeholder="请输入"
                />,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="　是否柜体" colon={false}>
              {getFieldDecorator('isCabinet')(
                <Select
                  placeholder="请选择"
                  allowClear
                  style={{ width: '100%' }}
                >
                  <Option value="1">是</Option>
                  <Option value="0">否</Option>
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="　柜体名称" colon={false}>
              {getFieldDecorator('cabinet')(
                <Select
                  showSearch
                  allowClear
                  labelInValue
                  placeholder="请选择"
                  notFoundContent={null}
                  onSearch={this.searchCabinet}
                  onChange={this.handleChangeCabinet}
                  onBlur={() => this.onBlurSelect('cabinet', 'cabinetList')}
                  filterOption={(input: any, option: any) => option.props.children
                    .toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {cabinetList.map((item: any) => (
                    <Option value={String(item.id)} key={item.id}>
                      {item.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="　货架地堆" colon={false}>
              {getFieldDecorator('shelves')(
                <Select
                  showSearch
                  allowClear
                  labelInValue
                  placeholder="请选择"
                  notFoundContent={null}
                  onSearch={this.searchShelves}
                  onChange={this.handleChangeShelves}
                  onBlur={() => this.onBlurSelect('shelves', 'shelfList')}
                  filterOption={(input: any, option: any) => option.props.children
                    .toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {shelfList.map((item: any) => (
                    <Option value={`${String(item.id)}|${item.type}`} key={item.id}>
                      {item.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <FormItem label="　　运单号" colon={false}>
              {getFieldDecorator('expCode')(
                <Input
                  allowClear
                  placeholder="请输入"
                />,
              )}
            </FormItem>
          </Col>
          <Col md={18} sm={24}>
            <div className="flexFeView">
              <Button
                type="primary"
                htmlType="submit"
                className="smallButton"
              >
                查询
              </Button>
              <Button
                type="primary"
                className="addButton smallButton marginL16"
                onClick={this.handleReset}
              >
                重置
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const {
      current,
      pageSize,
      offlineDialog,
      operationInfo,
      backDialog,
      note,
      reasonType,
    } = this.state;

    const {
      logisCenterTaking: { data },
      loading,
      INITINFO: { withdrawReasonList },
    } = this.props;

    const contentObj = data.content.find((item: any) => item.current === current);
    const list = (contentObj ? contentObj.list : []) || [];

    const { batchOperaction } = this.state;
    const rowSelection: any = {
      columnWidth: 60,
      selectedRowKeys: batchOperaction.map((item: any) => item.id),
      onChange: (selectedRowKeys: number, selectedRows: any) => {
        this.setState({ batchOperaction: selectedRows });
      },
      getCheckboxProps: (record: any) => ({
        disabled: record.state === 0,
        name: record.name,
      }),
    };

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          {this.renderSearchFormElem()}
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={() => this.handleBatchOperation(true, 0)}
            >
              批量标记待盘点
            </Button>
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={() => this.handleBatchOperation(true, 1)}
            >
              批量取消待盘点
            </Button>
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={() => this.handleBatchOperation(true, 2)}
            >
              批量催取短信
            </Button>
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={this.handelExportExcel}
            >
              导出EXCEL
            </Button>
            {/* <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={this.handleChangeVisble}
            >
              打印
            </Button> */}
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={() => this.handleBatchOperation(true, 4)}
            >
              批量标记退回
            </Button>
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={() => this.handleBatchOperation(true, 3)}
            >
              批量签收
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={list}
            pagination={false}
            rowSelection={rowSelection}
            loading={loading}
            scroll={{ x: 1600 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
          {(current > 1 || list.length > 0) && (
            <Pagination
              current={current}
              pageSize={pageSize}
              total={data.count}
              length={list.length}
              showCount={this.handleShowCount}
              onChange={this.onSelectChange}
              onShowSizeChange={this.onShowSizeChange}
            />
          )}
        </Card>

        <div style={{ background: '#ffffff' }} />

        <Modal
          title="确认提示"
          style={{ top: 200 }}
          visible={offlineDialog}
          onOk={this.handleConfirm}
          onCancel={() => this.handleBatchOperation(false)}
        >
          <p>您确定要{operationInfo.label}吗？</p>
        </Modal>

        <Modal
          title="退回原因"
          visible={backDialog}
          onOk={this.handleConfirm}
          onCancel={this.handleCloseSettingBack}
        >
          <Form className="tableListForm">
            <Row>
              <Col md={20} sm={20}>
                <Form.Item label="　退回原因" colon={false}>
                  <Select
                    onChange={this.handChangeReasonType}
                    value={String(reasonType)}
                  >
                    <Option key={0} value="0">
                      请选择
                    </Option>
                    {withdrawReasonList.map((item: any) => (
                      <Option key={item.reasonType} value={String(item.reasonType)}>
                        {item.reasonDesc}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col md={20} sm={20}>
                <Form.Item label="　　　备注" colon={false}>
                  <TextArea
                    rows={4}
                    value={note}
                    onChange={this.handleChangeNote}
                  />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Modal>

        <PrintElemInfo dataList={list} />
      </>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
